package org.example.day05;

/**
 * 第二章节2.2.9:synchronized修饰静态方法与代码块synchronized(xxx.class)
 */
public class MyThread4 {
    //synchronized修饰静态方法，默认使用的锁是类对象，这里是MyThread4.class.
    //线程A和线程B调用的方法都用了同一把锁，达到线程同步
    synchronized public static void printA(){
        try {
            System.out.println("线程名称为: " + Thread.currentThread().getName() + " 进入printA的时间: " + System.currentTimeMillis());
            Thread.sleep(3000);
            System.out.println("线程名称为: " + Thread.currentThread().getName() + " 推出printA: " + System.currentTimeMillis());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    synchronized public static void printB(){
        System.out.println("线程名称为: " + Thread.currentThread().getName() + " 进入printB的时间: " + System.currentTimeMillis());
        System.out.println("线程名称为: " + Thread.currentThread().getName() + " 推出printB: " + System.currentTimeMillis());
    }

    public static void main(String[] args) throws InterruptedException {
        Thread4A ta = new Thread4A();
        ta.setName("A");
        ta.start();
        Thread.sleep(100); //确保A先拿到锁
        Thread4B tb = new Thread4B();
        tb.setName("B");
        tb.start();
    }
}

class Thread4A extends Thread{
    @Override
    public void run() {
        MyThread4.printA();
    }
}

class Thread4B extends Thread{
    @Override
    public void run() {
        MyThread4.printB();
    }
}